﻿#ifndef JZ_MODBUS_PARAM_H_
#define JZ_MODBUS_PARAM_H_

#include <inttypes.h>
#include <QVector>
#include <QVariant>
#include <QDataStream>
#include <QSerialPort>

enum {
    Modbus_rtuClient,
    Modbus_tcpClient,
    Modbus_rtuServer,
    Modbus_tcpServer,
};

enum {
    Param_Coil,
    Param_DiscreteInput,
    Param_HoldingRegister,
    Param_InputRegister,
};

class JZModbusStrategy
{
public:
    JZModbusStrategy();

    bool recvNotify;
    bool autoRead;
    int autoReadTime;
};
QDataStream &operator<<(QDataStream &s, const JZModbusStrategy &param);
QDataStream &operator>>(QDataStream &s, JZModbusStrategy &param);

class JZModbusParam
{
public:
    enum {
        Data_bit,
        Data_int16,
        Data_uint16,
        Data_int32,
        Data_uint32,
        Data_int64,
        Data_uint64,
        Data_float,
        Data_double,
    };

    static QStringList addrTypeList();
    static QStringList dataTypeList();

    JZModbusParam();

    int byteSize() const;
    int addrEnd() const;
    void setValue(const QVariant &v);

    void unpack(const QVector<uint16_t>& buffer);
    void pack(QVector<uint16_t>& buffer);

    QString name;
    int addr;
    int addrType;
    int dataType;
    QVariant value;
    QDataStream::ByteOrder byteOrder;  //远端的字节序，本地总是小端
    QString memo;  
};
QDataStream &operator<<(QDataStream &s, const JZModbusParam &param);
QDataStream &operator>>(QDataStream &s, JZModbusParam &param);

class JZModbusParamMap
{
public:
    void clear();

    bool add(const JZModbusParam &value);
    void remove(int addr);
    JZModbusParam *param(int addr);    
    QList<int> paramList();
    bool contains(int addr);
    int count();        

protected:
    int indexOf(int addr);

    QList<JZModbusParam> m_params;
};

//JZModbusConnetInfo
class JZModbusConnetInfo
{
public:
    JZModbusConnetInfo();

    bool isRtu() const;
    bool isMaster() const;

    int modbusType;
    int slave;
    bool plcMode;

    QString portName;
    int baud;
    QSerialPort::DataBits dataBit;
    QSerialPort::Parity parityBit;
    QSerialPort::StopBits stopBit;

    QString ip;
    int port;
};
QDataStream &operator<<(QDataStream &s, const JZModbusConnetInfo &param);
QDataStream &operator>>(QDataStream &s, JZModbusConnetInfo &param);

//JZModbusConfig
class JZModbusConfig
{
public:
    JZModbusConfig();

    bool isRtu() const;
    bool isMaster() const;

    JZModbusConnetInfo conn;
    QMap<int,JZModbusStrategy> strategyMap;
    QList<JZModbusParam> paramList;    
};
QDataStream &operator<<(QDataStream &s, const JZModbusConfig &param);
QDataStream &operator>>(QDataStream &s, JZModbusConfig &param);

#endif // !JZ_MODBUS_VALUE_H_
